<?php
// 应用公共文件

// 账户替换
if (!function_exists('hide')) {
    /**
     * [hideStar 用户名、邮箱、手机账号中间字符串以*隐藏]
     * @param  [string] $str [传过来字符串]
     * @return [string]      [返回带*字符串]
     */
    function hide($str) { 
        if (strpos($str, '@')) {
            $arr = explode('@',$str);
            if( strlen($arr[0]) <= 5 ){
                return preg_replace('/([\d\w-]{1})(.*?)([\d\w-]{1})@/', '$1***$3@', $str,-1,$count);
            }else{
                return preg_replace('/([\d\w-]{2})(.*?)([\d\w-]{2})@/', '$1****$3@', $str,-1,$count);
            }
        } else { 
            $pattern = '/(1[3458]{1}[0-9])[0-9]{4}([0-9]{4})/i'; 
            if (preg_match($pattern, $str)) { 
                $rs = preg_replace($pattern, '$1****$2', $str); 
            } else { 
                $rs = substr($str, 0, 3) . "***" . substr($str, -1); 
            } 
        } 
        return $rs; 
    } 
}

// 获取客户端ip地址
if (!function_exists('get_client_ip')) {
    /**
     * 获取客户端IP地址
     * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param bool $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    function get_client_ip($type = 0, $adv = false) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if($adv){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos    =   array_search('unknown',$arr);
                if(false !== $pos) unset($arr[$pos]);
                $ip     =   trim($arr[0]);
            }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip     =   $_SERVER['HTTP_CLIENT_IP'];
            }elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip     =   $_SERVER['REMOTE_ADDR'];
            }
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}
// API应用的数据返回
if (!function_exists('api_response')) {
    /**
     * APi返回数据
     */
    function api_response($code = 200, $message = '',$data = [], $count = 0)
    {
        $response['code']    = $code;
        $response['message'] = $message;

        if( $count ){
            $response['count'] = $count;
        }

        if( $code == 200 && $data !== null ){
            if( empty($data) === false ){
                if( $data instanceof \think\model\Collection ){
                    $response['data'] = $data->toArray();
                }else{
                    $response['data'] = $data;
                }
            }else{
                throw new \app\api\exception\ResourceNotFoundException();
            }
        }
        exit(json_encode($response,JSON_UNESCAPED_UNICODE));
    }
}

//无限极
function get_Tree(array $data = [],$fid = "pid")
{
    $tempArr  = [];
    foreach ($data as $value) {
        $tempArr[$value[$fid]][] = $value;
    }
    return recursion_deal_tree($tempArr);
}

function recursion_deal_tree($data,$level = 0,$pk = "id",$childKey = "children")
{
    foreach ($data[$level] as $key => $value) {
        if (array_key_exists($value[$pk],$data)) {
            $data[$level][$key][$childKey] = recursion_deal_tree($data,$value[$pk],$pk,$childKey);
        }
    }
    return $data[$level];
}

/**
 * 获取绝对路径
 */
function getAbsolutePath($path)
{
    if (!empty($path) && !preg_match('/^data:image\/.+base64/', $path) && preg_match('/^https?:\/\//', $path) <= 0) {
        return request()->domain() . '/' . ltrim($path, '/');
    }
    return (string) $path;
}


/**
 * 能用的随机数生成
 * @param string $type 类型 alpha/alnum/numeric/nozero/unique/md5/encrypt/sha1
 * @param int    $len  长度
 * @return string
 */
function build($type = 'alnum', $len = 8)
{
    switch ($type) {
        case 'alpha':
        case 'alnum':
        case 'numeric':
        case 'nozero':
            switch ($type) {
                case 'alpha':
                    $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                    break;
                case 'alnum':
                    $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                    break;
                case 'numeric':
                    $pool = '0123456789';
                    break;
                case 'nozero':
                    $pool = '123456789';
                    break;
            }
            return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len);
        case 'unique':
        case 'md5':
            return md5(uniqid(mt_rand()));
        case 'encrypt':
        case 'sha1':
            return sha1(uniqid(mt_rand(), true));
    }
}

/**
 * 获取全球唯一标识
 * @return string
 */
function uuid()
{
    return sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0xffff)
    );
}
/**
 * 获取一个基于时间偏移的Unix时间戳
 *
 * @param string $type     时间类型，默认为day，可选minute,hour,day,week,month,quarter,year
 * @param int    $offset   时间偏移量 默认为0，正数表示当前type之后，负数表示当前type之前
 * @param string $position 时间的开始或结束，默认为begin，可选前(begin,start,first,front)，end
 * @param int    $year     基准年，默认为null，即以当前年为基准
 * @param int    $month    基准月，默认为null，即以当前月为基准
 * @param int    $day      基准天，默认为null，即以当前天为基准
 * @param int    $hour     基准小时，默认为null，即以当前年小时基准
 * @param int    $minute   基准分钟，默认为null，即以当前分钟为基准
 * @return int 处理后的Unix时间戳
 */
function unixtime($type = 'day', $offset = 0, $position = 'begin', $year = null, $month = null, $day = null, $hour = null, $minute = null)
{
    $year = is_null($year) ? date('Y') : $year;
    $month = is_null($month) ? date('m') : $month;
    $day = is_null($day) ? date('d') : $day;
    $hour = is_null($hour) ? date('H') : $hour;
    $minute = is_null($minute) ? date('i') : $minute;
    $position = in_array($position, array('begin', 'start', 'first', 'front'));

    switch ($type) {
        case 'minute':
            $time = $position ? mktime($hour, $minute + $offset, 0, $month, $day, $year) : mktime($hour, $minute + $offset, 59, $month, $day, $year);
            break;
        case 'hour':
            $time = $position ? mktime($hour + $offset, 0, 0, $month, $day, $year) : mktime($hour + $offset, 59, 59, $month, $day, $year);
            break;
        case 'day':
            $time = $position ? mktime(0, 0, 0, $month, $day + $offset, $year) : mktime(23, 59, 59, $month, $day + $offset, $year);
            break;
        case 'week':
            $time = $position ?
                mktime(0, 0, 0, $month, $day - date("w", mktime(0, 0, 0, $month, $day, $year)) + 1 - 7 * (-$offset), $year) :
                mktime(23, 59, 59, $month, $day - date("w", mktime(0, 0, 0, $month, $day, $year)) + 7 - 7 * (-$offset), $year);
            break;
        case 'month':
            $time = $position ? mktime(0, 0, 0, $month + $offset, 1, $year) : mktime(23, 59, 59, $month + $offset, cal_days_in_month(CAL_GREGORIAN, $month + $offset, $year), $year);
            break;
        case 'quarter':
            $time = $position ?
                mktime(0, 0, 0, 1 + ((ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) - 1) * 3, 1, $year) :
                mktime(23, 59, 59, (ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) * 3, cal_days_in_month(CAL_GREGORIAN, (ceil(date('n', mktime(0, 0, 0, $month, $day, $year)) / 3) + $offset) * 3, $year), $year);
            break;
        case 'year':
            $time = $position ? mktime(0, 0, 0, 1, 1, $year + $offset) : mktime(23, 59, 59, 12, 31, $year + $offset);
            break;
        default:
            $time = mktime($hour, $minute, 0, $month, $day, $year);
            break;
    }
    return $time;
}

if (!function_exists('https_request')) {
    function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
